<script setup>
import {ref} from 'vue';
import {ElMessage} from 'element-plus';
import {createMemberApi} from '@/service/member.js'; // 假设你有一个添加门店的 API
// 导入获取产品分类的api
import {getCategoryListApi} from '@/service/goods.js';
import {getCityListApi, getOpenedCityListApi} from '@/service/zone.js';
// 导入获取sourceTree的api
import {getSourceTreeApi} from '@/service/source.js';
import {RoleArray} from "../config/common.js";

// 导入添加联系方式的组件
import ContactAdd from './contact-add.vue';
// 商品模型
import MemberWedding from "@/pages/member/components/member-wedding.vue";

const emit = defineEmits(['reload']);
const reload = () => {
  emit('reload');
}

// 将RoleArray转换成对象value做key, label做value
const roleMap = ref(RoleArray.reduce((acc, cur) => {
  acc[cur.value] = cur.label;
  return acc;
}, {}));


const drawerVisible = ref(false);
const ruleForm = ref({
  category_id: '',
  source_id: '',
  remark: '',
  city_id: '',
  zone: [],
});

const contacts = ref([]);

const rules = ref({
  // 其他验证规则
  category_id: [
    {required: true, message: '请选择信息类型', trigger: 'change'}
  ],
  source_id: [
    {required: true, message: '请选择渠道', trigger: 'change'}
  ],
  city_id: [
    {required: true, message: '请选择城市', trigger: 'change'}
  ],
  remark: [
    {required: false, message: '请输入备注', trigger: 'blur'}
  ]
});

// 加载产品分类
const categoryList = ref([]);
const fetchCategoryList = () => {
  getCategoryListApi().then(res => {
    if (res.code === 200) {
      categoryList.value = res.data.list;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 加载渠道树
const sourceTree = ref([]);
const fetchSourceTree = () => {
  getSourceTreeApi().then(res => {
    sourceTree.value = res.data.tree;
  });
};

// 重置form表单
const resetForm = () => {
  ruleForm.value = {
    category_id: '',
    source_id: '',
    city_id: '',
    zone: [],
    remark: '',
  };
};

const zoneList = ref([]);
const openedList = ref([]);
// 获取开放的城市列表
const fetchOpenedList = () => {
  getOpenedCityListApi().then(res => {
    if (res.code === 200) {
      openedList.value = res.data.list;
    }
  });
};

// 获取城市列表
const selected = ref([]);
const zoneRef = ref(null);
const fetchCityList = (id) => {
  // 清空区域
  selected.value = [];
  getCityListApi({id, is_open: 1}).then(res => {
    if (res.code === 200) {
      zoneList.value = res.data.list;
    }
  });
};


// 选择区域
const chooseZone = (e) => {
  // 将选择的区域添加到已选区域form.zone
  const zone = zoneList.value.find(item => item.id === e);
  if (zone) {
    // 判断selected中是否已经存在
    if (!selected.value.find(item => item.id === zone.id)) {
      selected.value.push(zone);
      ruleForm.value.zone = selected;
    }
  }
};

// 删除已选区域
const removeItem = (item) => {
  const index = selected.value.findIndex(i => i.id === item.id);
  selected.value.splice(index, 1);
  productForm.zone = selected;
};


// 显示添加门店的抽屉，并清空表单
const showDrawer = () => {
  drawerVisible.value = true;
  fetchCategoryList();
  fetchSourceTree();
  fetchOpenedList();
  resetForm();
};

// 显示添加联系方式的弹窗
const contactAddRef = ref(null);
const showAppendContact = () => {
  // 处理添加的联系方式
  contactAddRef.value.openDialog();
};

// 接收添加的联系方式
const appendContact = (contact) => {
  // 将联系方式添加到门店信息中
  contacts.value = [...contacts.value, contact];
}

const memberWeddingRef = ref(null);
const handleSubmit = async () => {
  try {
    ruleForm.value.zone = selected.value;
    let params = {
      ...ruleForm.value,
      contacts: contacts.value,
      product: memberWeddingRef.value.getFormValue()
    }
    const resp = await createMemberApi(params);
    if (resp.code === 200) {
      ElMessage.success(resp.msg);
      drawerVisible.value = false;
      // 添加成功后，刷新门店列表
      reload();
    } else {
      ElMessage.error(resp.msg);
    }

  } catch (error) {
    ElMessage.error('客资添加失败，请稍后重试');
  }
};

// 删除联系方式
const handleDeleteContact = (contact) => {
  contacts.value = contacts.value.filter(item => item !== contact);
};

defineExpose({
  showDrawer
});
</script>

<template>
  <el-drawer
      title="添加客资"
      v-model="drawerVisible"
      size="30%"
      header-class="drawer-header"
      :close-on-click-modal="false"
  >
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" label-position="top">
      <el-form-item label="信息类型" prop="category_id">
        <el-select v-model="ruleForm.category_id" placeholder="请选择信息类型">
          <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="渠道" prop="source_id">
        <el-cascader v-model="ruleForm.source_id" :options="sourceTree"
                     :props="{label:'title', value:'id' ,checkStrictly: true, emitPath: false }"
                     placeholder="请选择父级渠道"
                     style="width:100%"></el-cascader>
      </el-form-item>
      <el-form-item label="联系方式" prop="contacts">
          <el-button type="danger" @click="showAppendContact" style="margin-bottom: 10px;">添加联系方式</el-button>
          <el-table :data="contacts" border>
            <el-table-column prop="type" label="类型" align="center">
              <template #default="{row}">
                <span>{{ row.type == 1 ? '电话' : '微信' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="称呼" align="center"/>
            <el-table-column prop="contact" label="联系方式"/>
            <el-table-column prop="role" label="角色" align="center">
              <template #default="{row}">
                <span>{{ roleMap[row.role] ? roleMap[row.role] : '异常'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{row}">
                <el-button type="danger" size="small" @click="handleDeleteContact(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
      </el-form-item>
      <el-form-item label="城市" prop="city_id">
        <el-row :gutter="10" style="width:100%">
          <el-col :span="12">
            <el-select v-model="ruleForm.city_id" placeholder="请选择城市"
                       @change="fetchCityList(ruleForm.city_id)">
              <el-option
                  v-for="item in openedList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-select ref="zoneRef" filterable clearable placeholder="请选择区域"
                       @change="chooseZone">
              <el-option
                  v-for="item in zoneList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="已选区域" prop="zone">
        <el-tag v-for="item in selected" :key="item.id" closable @close="removeItem(item)" style="margin-right: 6px;">
          {{ item.name }}
        </el-tag>
      </el-form-item>
      <!-- 其他表单项 -->
      <member-wedding ref="memberWeddingRef"></member-wedding>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注" :rows="4"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="drawerVisible = false">取消</el-button>
      </el-form-item>
    </el-form>

    <contact-add ref="contactAddRef" @receive="appendContact" :contacts="contacts"></contact-add>
  </el-drawer>
</template>

<style scoped lang="less">
.drawer-header {
  background-color: #f0f2f5;
}
</style>
